package crons

import (
	"APT/internal/dao"
	"APT/internal/library/airhousePublicApi"
	"APT/internal/model/entity"
	"context"
	"database/sql"
	"errors"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/frame/g"
)

func AhPublicApiRoomTypeAndRates(ctx context.Context) (err error) {
	var (
		ListRoomTypesAndRates *airhousePublicApi.ListRoomTypesAndRatesJSONDataResponse
		PmsRoomType           []*entity.PmsRoomType
		UpdateRow             int64
		Logger                = g.Log().Path("logs/CRON/AhPublicApiRoomTypeAndRates")
	)
	Logger.Info(ctx, "--[执行开始]----------------------------------------")
	g.DB().SetLogger(Logger)

	if err = dao.PmsRoomType.Ctx(ctx).Scan(&PmsRoomType); err != nil && !errors.Is(err, sql.ErrNoRows) {
		Logger.Error(ctx, "同步房型和费率计划数据失败", err)
		return
	}

	for key, v := range PmsRoomType {
		// 查询房型和费率计划
		if ListRoomTypesAndRates, err = airhousePublicApi.GetListRoomTypesAndRates(ctx, &airhousePublicApi.ListRoomTypesAndRatesRequest{
			PropertyId: v.Puid,
			RoomTypeId: v.Uid,
		}); err != nil {
			Logger.Error(ctx, "同步房型和费率计划数据失败 物业 ID:"+v.Puid, err)
			continue
		}
		for _, ListRoomTypesAndRatesData := range ListRoomTypesAndRates.Data {
			RatePlanId := ""
			RatePlanIndex := 0
			for RatePlansIndex, RatePlans := range ListRoomTypesAndRatesData.RatePlans {
				if RatePlans.Name == "Standard Rate" {
					RatePlanId = gvar.New(RatePlans.ID).String()
					RatePlanIndex = RatePlansIndex
				}
			}
			if RatePlanId == v.RatePlanId {
				Logger.Error(ctx, "同步房型和费率 RatePlansId 一致无需同步")
				continue
			}
			// 更新房型信息
			if UpdateRow, err = dao.PmsRoomType.Ctx(ctx).Where(g.MapStrAny{
				dao.PmsRoomType.Columns().Uid: ListRoomTypesAndRatesData.RoomType.ID,
			}).OmitEmptyData().Data(&entity.PmsRoomType{
				BasePrice:              gvar.New(ListRoomTypesAndRatesData.RoomTypeMinBaseRate).Float64(),
				RatePlanId:             RatePlanId,
				CleaningFee:            0,
				AdditionalGuestAmounts: gvar.New(ListRoomTypesAndRatesData.RatePlans[RatePlanIndex].PerDayPricing.AdditionalGuestAmounts[0].Amount).Float64(),
			}).UpdateAndGetAffected(); err != nil {
				Logger.Error(ctx, "同步房型和费率计划数据失败 物业 ID:"+v.Uid, err)
				return
			}
			if UpdateRow != 1 {
				Logger.Error(ctx, "同步房型和费率计划数据失败 物业 ID:"+v.Uid, err)
				continue
			}
		}
		Logger.Infof(ctx, "[INDEX]:%d", key)
	}
	Logger.Info(ctx, "执行成功")
	return
}
